// redis/redis.module.ts
import { Module, Global, DynamicModule, Logger } from '@nestjs/common';
import Redis from 'ioredis';
import { ConfigService } from '@nestjs/config';
import { RedisService } from './redis.service';

@Global()
@Module({})
export class RedisModule {
  private static readonly _logger = new Logger('Redis服务');

  static forRoot(): DynamicModule {
    const redisProvider = {
      provide: 'REDIS_CLIENT',
      useFactory: async (configService: ConfigService) => {
        const host = configService.get('REDIS_HOST');
        const port = configService.get('REDIS_PORT');
        const password = configService.get('REDIS_PASSWORD');
        const db = configService.get('REDIS_DB');
        const name = configService.get('REDIS_NAME');

        const redisClient = new Redis({
          host,
          port,
          password: password || undefined,
          db: Number(db) || 0,
          connectionName: name || 'herin-redis',
        });

        // 连接监听
        redisClient.on('connect', () => {
          this._logger.log(`Redis connected: ${name || 'default'} (DB ${db})`);
        });

        redisClient.on('error', error => {
          this._logger.error(`Redis connection error: ${error.message}`);
        });

        // 验证连接
        try {
          await redisClient.ping();
          this._logger.log(`Redis ping successful`);
        } catch (error) {
          this._logger.error(`Failed to connect to Redis: ${error.message}`);
          throw error;
        }

        return redisClient;
      },
      inject: [ConfigService],
    };

    return {
      module: RedisModule,
      providers: [redisProvider, RedisService],
      exports: [RedisService],
    };
  }
}
